package cn.itcast.filter;


import cn.itcast.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


//@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.转为http请求和响应对象
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //2.获取请求路径,如果是登录请求的话,需要放行
        String url = request.getRequestURI();
        if (url.contains("/login")) {
            //3.直接放行
            filterChain.doFilter(request, response);
            return;
        }
        //4.不是登陆的话,需要获取请求头中的令牌
        String jwt = request.getHeader("token");
        //5.判断令牌是否有效
        try {
            JwtUtils.parseJWT(jwt);
            log.info("令牌合法,放行!!!!!!!!!!!!!!!!!!!!");
            //6.放行(没有异常)
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            response.setStatus(401);
        }



    }
}
